import URL from '@/config/url'
import store from '@/store/modules/index'

const utils = {
	
	// 发送请求
	uniRequest({ url, data, method = 'POST',header } = {}) {
		// #ifdef MP-WEIXIN
		   let X_FROM  = 'miniprogram'
		// #endif
		//  #ifdef APP-PLUS 
		   let  X_FROM = '';
		   if(uni.getSystemInfoSync().platform == 'ios'){
			X_FROM  = 'ios'
		   }else if(uni.getSystemInfoSync().platform === 'android') {
			X_FROM  = 'android'
		   }
		//  #endif 
		//  #ifdef H5 
		   let X_FROM  = 'h5'
		//  #endif 
		let headers = {
			'access-token' :store.state.token || '',
			'user-id' : store.state.userId || '',
			'market-id' : store.state.marketId || '',
			X_FROM:X_FROM
		}
		return new Promise((resolve, reject) => {
			uni.request({ url, method, data,header: headers,
				success(res) {
					resolve(res.data)
					if(res.data.code == '-5'){
					    var t = this;
					    uni.showModal({
					        title: "提示！",
					        content: "请先登录！",
					        success: function(s) {
					            if (s.confirm) {
					               uni.navigateTo({
					                url: '/pages_login/pages/login/login/index',
					               });
					            }
					        }
					    });
					}
				},
				fail(err) {
					reject(err)
				}
			})
		})
	},

	// 登录
	login({ success } = {}) {
		uni.login({
			success: (res) => {
				console.log(res,'登录===')
				if (res.code) {
					if (typeof success === 'function') success(res)
				}
				else {
					this.hideLoading()
					this.showErr()
				}
			},
			fail: () => {
				this.hideLoading()
				this.showErr()
			}
		})
	},
	// 贮存当前页面
	getUrl() {
	    var pages = getCurrentPages() //获取加载的页面  
	    var currentPage = pages[pages.length - 1] //获取当前页面的对象  
	    var url = currentPage.route //当前页面url  
	    uni.setStorageSync('Router', `${url}`)  
	    var options = currentPage.options //如果要获取url中所带的参数可以查看options  
	    console.log(url);
	    console.log(options);
	    //参数多时通过&拼接url的参数  
	    if(options){
	        var urlWithArgs = url + '?'  
	        for (var key in options) {  
	        var value = options[key]  
	        urlWithArgs += key + '=' + value + '&'  
	        } 
		 urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)  
		        // wx.setStorageSync('Url', `/${urlWithArgs}`)  
		        uni.setStorageSync('Router', `${urlWithArgs}`) 
				console.log(urlWithArgs);
		    }
		},
	
	// 错误提示
	showErr({ title = '网络异常，请稍后再试', icon = 'none', duration = 1500, mask = false } = {}) {
		uni.showToast({ title, icon, duration, mask })
	},
	
	// 加载提示
	showLoading({ title = '加载中...', mask = true } = {}) {
		uni.showLoading({ title, mask })
	},
	
	// 隐藏加载提示
	hideLoading() {
		uni.hideLoading()
	},
	
	// 获取某个时间和现在的关系
	getTimeRelation(time, nowTime = Date.now()) {
		let nowDate = new Date(nowTime)  
		let timeDate = new Date(time)
		
		// 2分钟以内 => 刚刚
		if (nowTime - time < 120000) {   // 120000: 2分钟
			return '刚刚'
		}
		// 今天
		else if (timeDate.toDateString() === nowDate.toDateString()) {
			// 1小时以内 => xx分钟前
			if (nowTime - time < 3600000) {  // 3600000：1小时
				return Math.floor((nowTime - time) / 60000) + '分钟前'   // 60000：1分钟
			}
			// 1小时以后 => xx小时前
			else {
				return Math.floor((nowTime - time) / 3600000) + '小时前'  // 3600000：1小时
			}
		}
		// 昨天 => 昨天 xx:xx
		else if (this.isYesterday(timeDate, nowDate)) {
			return '昨天 ' + this.getFormatDate(time, 'hh:mm')
		}
		else {
			// 今年 => xx-xx xx:xx
			if (timeDate.getFullYear() === nowDate.getFullYear()) {
				return this.getFormatDate(time, 'MM-dd hh:mm')
			}
			// 其他年份
			else {
				// 2000年以后 => xx-xx-xx xx:xx
				if (timeDate.getFullYear() > 2000) {
					return this.getFormatDate(time, 'yy-MM-dd hh:mm')
				}
				// 2000年以前 => xxxx-xx-xx xx:xx
				else {
					return this.getFormatDate(time, 'yyyy-MM-dd hh:mm')
				}
			}
		}
	},
	
	// 获取格式化日期
	getFormatDate(t, fmt = 'yyyy-MM-dd') {
		let time = t instanceof Date ? t : new Date(typeof t === 'string' ? t.replace(/\-/g, "/") : t)
		if (time instanceof Date && !isNaN(time.getTime())) {
			let o = {
				'M+': time.getMonth() + 1,
				'd+': time.getDate(),
				'h+': time.getHours(),
				'm+': time.getMinutes(),
				's+': time.getSeconds()
			}
			if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length))
			for (var k in o) {
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)))
			}
			return fmt
		}
		else {
			return 'NaN'
		}
	},
	
	// 图片预览
	toViewImg(index,imgData) { //type=1合同，type=2施工图纸
		let imgArr = imgData
		let urlType = Array.isArray(imgArr)
		// console.log(imgArr,'需要预览的图片')
		let imgUrl = []
		if (urlType) {
			imgArr.map(item => {
				imgUrl.push(item.path)
			})
		} else {
			imgUrl.push(imgArr.path)
		}
		uni.previewImage({
			current: index, //预览图片的下标
			urls: imgUrl //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
		});
	},
	
	// 获取两个时间戳之间的天数
	getDaysAndHours(blockingTime,dateNow){
		if(!dateNow){
			dateNow = new Date().getTime()
		}
		// let dateNow = new Date();  // 获取当前时间
		
		let timeDiff = blockingTime - dateNow;  // 时间差的毫秒数
		// timeDiff = 时间戳差值
		
		let days = Math.floor(timeDiff / (24 * 3600 * 1000)); // 计算出天数
		let leavel1 = timeDiff % (24 * 3600 * 1000); // 计算天数后剩余的时间
		let hours = Math.floor(leavel1 / (3600 * 1000)); // 计算天数后剩余的小时数
		// let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
		// let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
		
		// return days+'天'+hours+'小时';
		return days;
	},
	// 获取未来一天时间距现在的时分秒
	getFutreTime(dataTime){
		let nowTime = new Date()
		let timeDiff = dataTime - nowTime.getTime()
		
		// var hours = parseInt((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
		// var minutes = parseInt((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
		// var seconds = parseInt((timeDiff % (1000 * 60)) / 1000);
		
		let days = Math.floor(timeDiff / (24 * 3600 * 1000)); // 计算出天数
		let leavel1 = timeDiff % (24 * 3600 * 1000); // 计算天数后剩余的时间
		let hours = Math.floor(leavel1 / (3600 * 1000)); // 计算天数后剩余的小时数
		let leavel2 = timeDiff % (3600 * 1000); // 计算剩余小时后剩余的毫秒数
		let minutes = Math.floor(leavel2 / (60 * 1000)); // 计算剩余的分钟数
		let leavel3 = timeDiff % (60 * 1000); // 计算剩余分钟后剩余的毫秒数
		let seconds = Math.floor(leavel3 / 1000); // 计算剩余的秒数
		return hours+':'+minutes+':'+seconds
	},
	
	// 是否是昨天
	isYesterday(tDate, nDate = new Date()){
		let yesterDate = new Date(nDate.getTime() - 86400000)   // 86400000：一天
		return tDate.getYear() === yesterDate.getYear() && tDate.getMonth() === yesterDate.getMonth() && tDate.getDate() === yesterDate.getDate()
	},
	
	//获取后一个月日期(data为字符串年月日)
	getNowFormatDateTime(date){
	    let time = ''
	    if(date){
	        time=new Date(date).getTime()+30*24*60*60*1000;
	    }else{
	        time=new Date().getTime()+30*24*60*60*1000;
	    }
	    let afterday=new Date(time);
	    let month=afterday.getMonth()+1;
	    let day=afterday.getDate();
		month = month<10?'0'+month:month;
		day = day<10?'0'+day:day;
	    return afterday=afterday.getFullYear() + "-" + month + "-" + day;
	},
	
		
	// js加法
	accAdd(arg1, arg2) {
		let r1, r2, m
		try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
		try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
		m = Math.pow(10, Math.max(r1, r2))
		return (this.accMul(arg1, m) + this.accMul(arg2, m)) / m;   
	},

	// js减法
	accSub(arg1, arg2) {
		let r1, r2, m
		try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
		try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
		m = Math.pow(10, Math.max(r1, r2));
		return (this.accMul(arg1, m) - this.accMul(arg2, m)) / m;  
	},

	// js乘法
	accMul(arg1, arg2) {
		let m = 0, s1 = arg1.toString(), s2 = arg2.toString()
		try { m += s1.split(".")[1].length } catch (e) { }
		try { m += s2.split(".")[1].length } catch (e) { }
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
	},

	// js除法
	accDiv(arg1, arg2) {    
		let t1 = 0, t2 = 0, r1, r2 
		try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
		try { t2 = arg2.toString().split(".")[1].length } catch (e) { }   
		r1 = Number(arg1.toString().replace(".", ""))    
		r2 = Number(arg2.toString().replace(".", ""))    
		return (r1 / r2) * Math.pow(10, t2 - t1)  
	},
	
}




export default utils
